package com.beiding.fastmock.fram;

import io.netty.util.concurrent.DefaultThreadFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.concurrent.CustomizableThreadFactory;

import java.util.Map;
import java.util.concurrent.*;

/**
 * @author 丁常磊
 * @date 2021/7/14 15:31
 */

@Slf4j
public class TaskCenter {

    private static ScheduledExecutorService scheduledExecutorService = new ScheduledThreadPoolExecutor(4, new CustomizableThreadFactory("防抖线程"));
    private static ExecutorService executorService = new ThreadPoolExecutor(8, 8, 20, TimeUnit.SECONDS, new LinkedBlockingDeque<>(), new DefaultThreadFactory("异步任务线程"));

    private static Map<String, Runnable> antiShakeTaskMap = new ConcurrentHashMap<>();

    /**
     * 防抖函数
     *
     * @param runnable
     * @param time
     */
    public static void antiShake(String topic, Runnable runnable, long time) {
        antiShakeTaskMap.put(topic, runnable);
        scheduledExecutorService.schedule(() -> {
            if (antiShakeTaskMap.get(topic) == runnable) {
                runnable.run();
            }
        }, time, TimeUnit.MILLISECONDS);
    }

    public static void task(Runnable runnable) {
        executorService.submit(runnable);
    }

}
